<template>
  <div class="root">
    <div class="checkedDate">
      <el-date-picker
        v-model="tempDate"
        align="right"
        type="date"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        placeholder="选择日期"
        :picker-options="pickerOptions">
      </el-date-picker>
      <el-button type="success" icon="el-icon-search" @click="checkedDateBtn()">去这天</el-button>
      <i class="el-icon-loading" v-if="diaryLoading"></i>
    </div>
    <div class="diaryList" :style="{height:this.$parent.fullHeight-150+'px'}" @scroll="diaryScroll" ref="diaryList">
      <el-timeline>
        <el-timeline-item :timestamp='diary.createTime' placement="top" v-for="diary in diarys" :key="diary.id">
          <el-card class="content">
            <h2>{{diary.title}}</h2>
            <p v-html="diary.content" />
            <span class="el-dropdown-link" @click="diaryComment(diary.id)">
              {{diary.commentCount}}条评论 查看<i class="el-icon-caret-bottom el-icon--right"></i>
              <i class="el-icon-loading" v-show="checkedDiaryId === diary.id && commentLoading"></i>
            </span>
            <el-button type="text" icon="el-icon-edit" @click="addComment(diary.id)">评论</el-button>
            <ul class="comment" v-show="checkedDiaryId === diary.id && commitFlag">
              <li v-for="comment in comments">
                <p><span style="color: #674c99">{{getTime(comment.time)}} : </span>{{comment.content}}</p>
              </li>
            </ul>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </div>
  </div>
</template>

<script>
    export default {
      name: "Diary",
      data(){
        return{
          tempDate: '', //用啦临时存选中时间
          checkedDate: '',  //按搜索时把临时间赋值给他
          diarys: [],
          comments: '',
          page: {
            totalPage:1,  //总页数
            currentPage: 1,  //当前页码
          },
          diaryLoading: true, //请求文章圈圈
          diaryScrollFlag: true,  //用来标识下拉是否要请求数据
          commentLoading: false ,  //评论加载中
          checkedDiaryId: '' ,//选中评论的ID
          commitFlag: false,  //显示/隐藏评论

          //时间选择
          pickerOptions: {
            disabledDate(time) {
              return time.getTime() > Date.now();
            },
            shortcuts: [
              {
              text: '今天',
              onClick(picker) {
                picker.$emit('pick', new Date());
              }
            }, {
              text: '昨天',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', date);
              }
            }, {
              text: '一周前',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', date);
              }
            }, {
                text: '一月前',
                onClick(picker) {
                  const date = new Date();
                  let newMonth = date.getMonth();
                  let newYear = date.getFullYear();
                  let newDay = date.getDate();
                  //当是12月时
                  if(newMonth===0){
                    newYear--;
                    newMonth = 12;
                    newYear--;
                  }

                  let newTime = new Date(newYear+'-'+newMonth+'-'+newDay);
                  picker.$emit('pick', newTime);
                }
              }, {
                text: '一年前',
                onClick(picker) {
                  const date = new Date();
                  let newMonth = date.getMonth()+1;
                  let newYear = date.getFullYear()-1;
                  let newDay = date.getDate();

                  let newTime = new Date(newYear + '-' + newMonth + '-' + newDay);
                  picker.$emit('pick', newTime);
                }
              }
            ]
          },
        }
      },
      methods: {
        //按时间查询
        checkedDateBtn(){
          this.checkedDate = this.tempDate;
          this.diarys = [];
          this.page.currentPage = 1;
          this.requestDiaryCount();
          this.requestDiary();
        },

        //滑动查询
        diaryScroll(){
          let _this = this;
          let totalPage = this.page.totalPage;
          let currentPage = this.page.currentPage;
          let a = _this.$refs.diaryList.scrollHeight;  //滚动条
          let b = _this.$refs.diaryList.clientHeight; //可视区
          let c = _this.$refs.diaryList.scrollTop;  //距离顶部
          if (this.diaryScrollFlag && currentPage <= totalPage && b+c >= a-300) {
            this.diaryScrollFlag = false;
            this.requestDiary();
          }
          if (this.diaryScrollFlag && currentPage > totalPage && b+c >= a-300) {
            this.diaryScrollFlag = true;
            this.$message.warning('哦噢，到底了！！');
          }
        },

        //查看评论
        diaryComment(id){
          //取相反的值，实现隐藏显示的效果
          this.commitFlag = !this.commitFlag;
          //只有当点击不一样的id时让它显示
          if(this.checkedDiaryId!==id){
            this.commitFlag = true;
          }
          //为true才查询
          if(this.commitFlag){
            this.commentLoading = true;
            this.checkedDiaryId = id;
            this.comments = '';
            this.$axios({
              method: 'post',
              params: {
                id: id,
              },
              url: 'http://localhost:8081/findDiaryComment'
            }).then((response) => {
              this.commentLoading = false;
              this.comments = response.data;
            }).catch(() =>
              this.$message({
                message: '评论加载失败，刷新试试',
                type: 'error',
              })
            )
          }
        },

        //评论
        addComment(id) {
          this.$prompt('请输入评论内容', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern: /\S/,
            inputErrorMessage: '评论不能为空'
          }).then(({ value }) => {
            this.$axios({
              method: 'post',
              params: {
                id: id,
                content: value
              },
              url: 'http://localhost:8081/addComment'
            }).then(() => {
              this.diarys.forEach(function (e) {
                if(e.id===id){
                  e.commentCount+=1;
                }
              });

              this.$message({
                type: 'success',
                message: '评论成功'
              });
            }).catch(() =>
              this.$message({
                message: '评论失败，稍后试试',
                type: 'error',
              })
            )
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消输入'
            });
          });
        },

        //把时间转换成。。。前
        getTime(ms){
          let datime = Date.parse(ms);
          let msi = new Date().getTime();
          let cha = msi - datime;
          // 以下是获取时，分，秒，
          let yeas = cha / 1000 / 60 / 60 / 24 / 30 / 12;
          let months = cha / 1000 / 60 / 60 / 24 / 30;
          let weeks = cha / 1000 / 60 / 60 / 24 / 7;
          let days = cha / 1000 / 60 / 60 / 24;
          let hours = cha / 1000 / 60 /60;
          let minutes = cha / 1000 / 60;
          // 一下是声明一个字符串，然后判断月，周，天，时，分
          let str = '';
          if(yeas >= 1) {
            str = `${parseInt(yeas)} 年前`
          }else if(months >= 1){
            str = `${parseInt(months)} 月前`
          }else if(weeks >= 1){
            str = `${parseInt(weeks)} 周前`
          }else if(days >= 1){
            str = `${parseInt(days)} 天前`
          }else if(hours >= 1){
            str = `${parseInt(hours)} 小时前`
          }else if(minutes >= 1){
            str = `${parseInt(minutes)} 分钟前`
          }else{
            str = '刚刚'
          }
          return str
        },

        //查询数据
        requestDiary(){
          this.diaryLoading = true;
          this.$axios({
            method: 'post',
            params: {
              currentPage: this.page.currentPage,
              createTime: this.checkedDate
            },
            url: 'http://localhost:8081/findDiary'
          }).then((response) => {
            this.diarys = this.diarys.concat(response.data);
            this.page.currentPage++;
            this.diaryScrollFlag = true;
            this.diaryLoading = false;
          }).catch(() =>{
            this.$message({
              message: '加载失败，刷新试试',
              type: 'error',
            });
            this.diaryLoading = true;
            this.diaryScrollFlag = true;
          });
        },

        //查询数据条数
        requestDiaryCount(){
          this.$axios({
            method: 'post',
            params: {
              createTime: this.checkedDate
            },
            url: 'http://localhost:8081/findDiaryCount',
          }).then((response) => {
            let diaryCount = response.data;
            let temp = diaryCount % 10;
            this.page.totalPage = temp===0 ? diaryCount/10:Math.ceil(diaryCount/10);
          }).catch(() =>
            this.$message({
              showClose: true,
              message: '抱歉，总记录条数请求失败,刷新试试',
              type: 'error',
            })
          );
        }
      },
      mounted() {
        this.requestDiaryCount();
        this.requestDiary();
      },
      watch :{
        'tempDate': {
          // 数据发生变化就会调用这个函数
          handler() {
            if(this.tempDate===null){
              this.checkedDate = '';
              this.diarys = [];
              this.page.currentPage = 1;
              this.requestDiaryCount();
              this.requestDiary();
            }
          },
          deep: true
        }
      }
    }
</script>

<style scoped>
  .root{
    background: #eaeaea;
    border-radius: 15px;
  }
  .checkedDate{
    width: 400px;
    margin: 0 auto 20px;
  }
  .diaryList{
    overflow-y: auto;
    min-height: 480px;
    width: 80%;
    min-width: 650px;
    margin: 0 auto;
  }
  .diaryList::-webkit-scrollbar {
    /*滚动条整体样式*/
    width : 5px;  /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }
  .diaryList::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
    background   : #535353;
  }
  .diaryList::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 10px;
    background   : #ededed;
  }
  .content{
    min-width: 550px;
    margin-right: 30px;
  }
  .comment{
    list-style: none;
    padding: 10px 10px 10px 10px;
  }
  .content li{
    background: rgb(235, 235, 235);
    width: 70%;
    border-radius: 3px;
  }
  /*评论文字样式*/
  .comment li p{
    font-size: 8px;
    padding: 5px 10px;
    word-wrap:break-word;
  }
  /*评论链接*/
  .el-dropdown-link{
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    cursor: pointer;
    color: #409EFF;
    display:inline-block;
    width: 150px;
  }
  .el-dropdown-link:active{
    color: #e60000;
  }

</style>

<style>
  .diaryList img:active{
    transition-duration: 300ms;
    width: 90%;
  }
  /*左侧点和竖条的样式*/
  .el-timeline-item__node {
    background-color: #40a790;
  }
  .el-timeline-item__tail {
    border-left: 2px solid #bababa;
  }
  /*时间样式*/
  .el-timeline-item{
    padding-bottom: 50px;
  }
</style>
